package moduloIndexacion.analizador;

import java.io.File;
import java.io.FileInputStream;
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;

import entidades.Extension;


public class AnalizadorPDF extends TemplateAnalizador{
	
	private PDFParser parser;
	private String parsedText;
	private PDFTextStripper pdfStripper;
	private PDDocument pdDoc;
	private COSDocument cosDoc;

	// PDFTextParser Constructor
	public AnalizadorPDF() {
		super.extension = new Extension ("pdf","Portable Document Format");
	}

	@Override
	protected String obtenerTexto() {
		String rutaAcceso = documento.getUbicacion()+documento.getNombre();
		File f = new File(rutaAcceso);
		
		try {
			parser = new PDFParser( new FileInputStream(f) );
		} catch (Exception e) {
			System.out.println("ERROR: Unable to open PDF Parser.");
			return null;
		}

		try {
			parser.parse();
			cosDoc = parser.getDocument();
			pdfStripper = new PDFTextStripper();
			pdDoc = new PDDocument(cosDoc);
			parsedText = pdfStripper.getText(pdDoc);
		} catch (Exception e) {
			System.out.println("ERROR: An exception occured in parsing the PDF Document.");
			e.printStackTrace();
			try {
				if (cosDoc != null) cosDoc.close();
				if (pdDoc != null) pdDoc.close();
			} catch (Exception e1) {
				e.printStackTrace();
			}
			return null;
		}
		System.out.println("Done.");
		return parsedText;
	}
}